import os
from django.conf import settings
from django.shortcuts import render
# from django.db import connection
from django.http import HttpResponse,JsonResponse       # 可以返回渲染的页面
# 人脸识别绘画
import sys
import cv2
import face_recognition
import json
# 读写excel
import numpy
import xlsxwriter as xw
import openpyxl
from xlutils.copy import copy

path1=os.path.abspath('./img_face/img')
path2=os.path.abspath('./img_face/zuce/')
path3=os.path.abspath('./img_face/duibi/')

def faceDuibi(path,lujing):
	face_image2 = face_recognition.load_image_file(path1+'/'+lujing)
	face_encodings2 = face_recognition.face_encodings(face_image2)
	if len(face_encodings2) == 1 :
		face2 = face_encodings2[0]
		img_path =path+"/zuce/"+lujing
		#打开文件：
		output_file_name = path2+'/mysql_face.xlsx'
		excel=openpyxl.load_workbook(output_file_name)
		#获取sheet：
		table = excel.get_sheet_by_name('Sheet')   #通过表名获取  
		#获取行数和列数：
		rows=table.max_row   #获取行数
		cols=table.max_column    #获取列数
		#获取单元格值：
		faceList =  []
		for i in range(rows-1):
			Data=table.cell(i+2,2).value  #获取表格内容，是从第一行第一列是从1开始的，注意不要丢掉 .value
			# faceAll.append(Data)
			results = face_recognition.compare_faces([decoding_FaceStr(Data)],face2,tolerance=0.5)
			faceList.append(results)
		
		if [True] in faceList:
			peopleList = {}
			peopleList["userName"]=table.cell(faceList.index([True])+2,3).value
			peopleList["nick_name"]=table.cell(faceList.index([True])+2,5).value
			peopleList["user_phone"]=table.cell(faceList.index([True])+2,6).value
			peopleList["user_email"]=table.cell(faceList.index([True])+2,7).value
			
			data={}
			data["token"] = True
			data["code"] = 200
			data["msg"] = "登录成功"
			# data["data"] = 
			# data["img"] = img_path
			data["data"] = peopleList
			return json.dumps(data,ensure_ascii=False)
		else :
			data={}
			data["token"] = False
			data["code"] = -1
			data["msg"] = "登录失败，你还没有注册o"
			return json.dumps(data,ensure_ascii=False)
	elif len(face_encodings2) > 1 :
		data={}
		data["token"] = False
		data["code"] = -1
		data["msg"] = "请选择单人照片"
		return json.dumps(data,ensure_ascii=False)
	else:
		data={}
		data["token"] = False
		data["code"] = -1
		data["msg"] = "未检测到人脸"
		return json.dumps(data,ensure_ascii=False)
def index(requests):
	return render(requests,"hailiang.html")
def upload(request):
	if request.method == "POST":
		myFile =request.FILES.get("myfile",None)
		if not myFile:
			data={}
			data["token"] = False
			data["code"] = -1
			data["msg"] =  "请选择可识别脸部图片"
			return JsonResponse(data)
		destination = open(os.path.join(os.path.dirname(__file__)+'/img',myFile.name),'wb+')    # 打开特定的文件进行二进制的写操作
		for chunk in myFile.chunks():      # 分块写入文件
			destination.write(chunk)
		destination.close()
		print(request,999)
		path = request.get_host()
		lujing = faceDuibi(path,myFile.name)
		return HttpResponse(lujing)



def zuce(request):
	return render(request,"zuce.html")
def zuceApi(request):
	if request.method == "POST":
		myFile =request.FILES.get("myfile",None)
		userName =request.POST.getlist('userName')
		userPassword = request.POST.getlist('userPassword')
		nick_name = request.POST.getlist('nick_name')
		user_phone = request.POST.getlist('user_phone')
		user_email = request.POST.getlist('user_email')
		
		if not myFile:
			data={}
			data["token"] = False
			data["code"] = -1
			data["msg"] =  "请选择可识别脸部图片"
			return JsonResponse(data)
		destination = open(os.path.join(os.path.dirname(__file__)+'/zuce/',myFile.name),'wb+')    # 打开特定的文件进行二进制的写操作
		for chunk in myFile.chunks():      # 分块写入文件
			destination.write(chunk)
		destination.close()
		print(request,999)
		path = request.get_host()
		face_people = zece_face(path,myFile.name)
		openpyxl_data = [
		    ('0', encoding_FaceStr(face_people), str(userName[0]), str(userPassword[0]), str(nick_name[0]), str(user_phone[0]),str(user_email[0])),
		]
		output_file_name = path2+'/'+'mysql_face.xlsx'
		zuce_save_excel(openpyxl_data, output_file_name)
		data={}
		data["msg"] = '注册成功'
		data["code"] = 200
		return JsonResponse(data)
		
def encoding_FaceStr(image_face_encoding):
        # 将numpy array类型转化为列表
        encoding__array_list = image_face_encoding.tolist()
        # 将列表里的元素转化为字符串
        encoding_str_list = [str(i) for i in encoding__array_list]
        # 拼接列表里的字符串
        encoding_str = ','.join(encoding_str_list)
        return encoding_str
 
def decoding_FaceStr(encoding_str):
        # print("name=%s,encoding=%s" % (name, encoding))
        # 将字符串转为numpy ndarray类型，即矩阵
        # 转换成一个list
        dlist = encoding_str.strip(' ').split(',')
        # 将list中str转换为float
        dfloat = list(map(float, dlist))
        face_encoding = numpy.array(dfloat)
        return face_encoding	
# 注册face人脸识别存取
def zece_face(path,lujing):
		face_image2 = face_recognition.load_image_file(path2+'/'+lujing)
		face_encodings2 = face_recognition.face_encodings(face_image2)
		return face_encodings2[0]
# 注册excel写入
def zuce_save_excel(target_list, output_file_name):
   
   data = openpyxl.load_workbook(output_file_name)
   print(data.get_named_ranges()) # 输出工作页索引范围
   print(data.get_sheet_names()) # 输出所有工作页的名称
   # 取第一张表
   sheetnames = data.get_sheet_names()
   table = data.get_sheet_by_name(sheetnames[0])
   table = data.active
   print(table.title) # 输出表名
   nrows = table.max_row # 获得行数
   ncolumns = table.max_column # 获得行数
   values = ["id","face_list","user_name","userPassword","nick_name","user_phone","user_email"]
   for i in range(len(target_list)):
     for j in range(len(values)):
        print(target_list[i][j],j)
        table.cell(nrows+1,j+1).value = target_list[i][j]
        if j == 1 :
           table.cell(nrows+1,1).value = nrows
     nrows = nrows + 1
   data.save(output_file_name)
   
def face_draw(request):
	if request.method == "POST":
		myFile = request.FILES.get("myfile",None)
		if not myFile:
			return HttpResponse("上传失败!")
		destination = open(os.path.join(path3+"/" ,myFile.name),'wb+')    # 打开特定的文件进行二进制的写操作
		for chunk in myFile.chunks():      # 分块写入文件
			destination.write(chunk)
		destination.close()
		face_image = face_recognition.load_image_file(path3+'/'+myFile.name)
		# face_image2 = face_recognition.load_image_file(path1+'\\'+lujing)
		face_encodings = face_recognition.face_encodings(face_image)
		face_locations= face_recognition.face_locations(face_image)
		
		# 对比是不是同一个人
		# face1 = face_encodings[0]
		# face2 = face_encodings[1]
		# results = face_recognition.compare_faces([face1],face2,tolerance=0.5)
		if len(face_encodings) > 0 :
			print('一共有',len(face_encodings),'人')
			for i in range(len(face_encodings)):
				face_encoding = face_encodings[(i-1)]
				face_location = face_locations[(i-1)]
				top,right,bottom,left = face_location
				# 画框
				cv2.rectangle(face_image,(left,top),(right,bottom),(0,255,0),2)
				
			face_image_rgb = cv2.cvtColor(face_image,cv2.COLOR_BGR2RGB)
			# 保存到本地
			cv2.imencode('.jpg', face_image_rgb)[1].tofile(path3+'/'+"aaa"+myFile.name)
			# cv2.imwrite(path3+"aaa"+myFile.name,face_image_rgb,[int(cv2.IMWRITE_JPEG_QUALITY),70])
			# cv2.imshow("nihao",face_image_rgb)
			cv2.waitKey(0)
			
			data={}
			data["faceImg1"] = 'http://'+request.get_host()+"/img/duibi/"+myFile.name
			data["faceImg2"] = 'http://'+request.get_host()+"/img/duibi/"+"aaa"+myFile.name
			data["faceNum"] = len(face_encodings)
			return JsonResponse(data)
		else:
			return  HttpResponse("没有检测到人脸")
		
	